package v1

import (
	dtonotify "sweetsunnyflower/app/http/dto/notify"
	"sweetsunnyflower/app/models/notify"
	"sweetsunnyflower/app/policies"
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/auth"
	"sweetsunnyflower/pkg/response"

	"github.com/gin-gonic/gin"
)

type NotifiesController struct {
	Controller
}

// 获取当前登录用户的通知
func (ctrl *NotifiesController) Index(c *gin.Context) {

	request := requests.NotifyQueryRequest{}
	if ok := requests.Validate(c, &request, requests.NotifyQuery); !ok {
		return
	}

	request.UserID = auth.CurrentIntUID(c)

	notifies := notify.GetByLatestId(request)

	notifiesFormat := make([]dtonotify.Content, 0)

	for _, v := range notifies {

		notifyContent, err := notify.UnmarshalContent([]byte(v.Content))
		if err != nil {
			response.Abort500(c, "解析通知内容失败，请稍后尝试~")
		}

		contentClass := dtonotify.ContentClass{
			Icon:    notifyContent.Icon,
			Title:   notifyContent.Title,
			Message: notifyContent.Message,
			Target:  notifyContent.Target,
		}

		notifyClass := dtonotify.Content{
			ID:        v.ID,
			Status:    v.Status,
			Type:      v.Type,
			Content:   contentClass,
			CreatedAt: v.CreatedAt,
		}

		notifiesFormat = append(notifiesFormat, notifyClass)
	}

	response.Data(c, notifiesFormat)
}

func (ctrl *NotifiesController) Show(c *gin.Context) {
	notifyModel := notify.Get(c.Param("id"))
	if notifyModel.ID == 0 {
		response.Abort404(c)
		return
	}
	response.Data(c, notifyModel)
}

func (ctrl *NotifiesController) Store(c *gin.Context) {

	request := requests.NotifyRequest{}
	if ok := requests.Validate(c, &request, requests.NotifySave); !ok {
		return
	}

	notifyModel := notify.Notify{
		// FieldName:      request.FieldName,
	}
	notifyModel.Create()
	if notifyModel.ID > 0 {
		response.Created(c, notifyModel)
	} else {
		response.Abort500(c, "创建失败，请稍后尝试~")
	}
}

func (ctrl *NotifiesController) Update(c *gin.Context) {

	notifyModel := notify.Get(c.Param("id"))
	if notifyModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyNotify(c, notifyModel); !ok {
		response.Abort403(c)
		return
	}

	request := requests.NotifyRequest{}
	if ok := requests.Validate(c, &request, requests.NotifySave); !ok {
		return
	}

	// notifyModel.FieldName = request.FieldName
	rowsAffected := notifyModel.Save()
	if rowsAffected > 0 {
		response.Data(c, notifyModel)
	} else {
		response.Abort500(c, "更新失败，请稍后尝试~")
	}
}

func (ctrl *NotifiesController) Delete(c *gin.Context) {

	notifyModel := notify.Get(c.Param("id"))
	if notifyModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyNotify(c, notifyModel); !ok {
		response.Abort403(c)
		return
	}

	rowsAffected := notifyModel.Delete()
	if rowsAffected > 0 {
		response.Success(c)
		return
	}

	response.Abort500(c, "删除失败，请稍后尝试~")
}
